import React, { useState, useEffect } from 'react';
import {
  HashRouter,
  Routes,
  Route,
  useNavigate,
  useLocation,
} from 'react-router-dom';
import {
  Layout,
  Menu,
  Avatar,
  Card,
  Row,
  Col,
  Typography,
  Space,
  Modal,
  Form,
  Input,
  Button,
  message,
  Dropdown
} from 'antd';
import {
  UserOutlined,
  HomeOutlined,
  InfoCircleOutlined,
  SettingOutlined,
  LogoutOutlined,
  CheckCircleOutlined
} from '@ant-design/icons';

import 'antd/dist/reset.css';

import Db from "./pages/table"
import Home from "./pages/home";

const { Header, Content } = Layout;
const { Title, Paragraph } = Typography;

// Token设置组件
const TokenSettingModal = ({ visible, onCancel, onSave }) => {
  const [form] = Form.useForm();

  form.setFieldValue("header", "access-token")

  const handleSubmit = () => {
    form.validateFields()
      .then(values => {
        onSave(values);
        message.success('Token设置成功');
        onCancel();
      })
      .catch(err => {
        console.log('验证失败:', err);
      });
  };

  return (
    <Modal
      title="设置Token"
      open={visible}
      onCancel={onCancel}
      footer={[
        <Button key="back" onClick={onCancel}>
          取消
        </Button>,
        <Button key="submit" type="primary" onClick={handleSubmit}>
          保存
        </Button>,
      ]}
    >
      <Form form={form} layout="vertical">
        <Form.Item
          name="header"
          label="请求头"
          rules={[{ required: true, message: '请输入请求头名称!' }]}
        >
          <Input placeholder="请求头名称" />
        </Form.Item>
        <Form.Item
          name="token"
          label="API Token"
          rules={[{ required: true, message: '请输入Token!' }]}
        >
          <Input placeholder="请输入您的API Token" />
        </Form.Item>
      </Form>
    </Modal>
  );
};

// 头部菜单组件
function AppMenu() {
  const navigate = useNavigate();
  const location = useLocation();
  const [selectedKey, setSelectedKey] = useState(location.pathname);

  useEffect(() => {
    setSelectedKey(location.pathname);
  }, [location.pathname]);

  const menuItems = [
    {
      key: '/',
      icon: <HomeOutlined />,
      label: '首页',
      template: <Home />
    },
    {
      key: '/about',
      icon: <InfoCircleOutlined />,
      label: '接口管理',
      template: <Db />,
    },
  ];

  const onMenuClick = ({ key }) => {
    navigate(key);
  };

  return (
    <Menu
      theme="light"
      mode="horizontal"
      selectedKeys={[selectedKey]}
      onClick={onMenuClick}
      items={menuItems}
      style={{
        fontWeight: 500,
        fontSize: 16,
        border: 'none',
        background: 'transparent',
      }}
      breakpoint="md"
    />
  );
}

function AppHeader() {
  const [tokenModalVisible, setTokenModalVisible] = useState(false);
  const [userMenuVisible, setUserMenuVisible] = useState(false);

  // 模拟从localStorage获取token
  const [token, setToken] = useState(localStorage.getItem('custom_api_token') || '');

  const handleSaveToken = (newToken) => {
    setToken(newToken);
    localStorage.setItem('custom_api_token', JSON.stringify(newToken));
  };

  const handleLogout = () => {
    setToken('');
    localStorage.removeItem('custom_api_token');
    message.success('已退出登录');
    setUserMenuVisible(false);
  };

  const userMenuItems = [
    {
      key: 'token',
      label: '设置Token',
      icon: <SettingOutlined />,
      onClick: () => {
        setTokenModalVisible(true);
        setUserMenuVisible(false);
      }
    },
    {
      key: 'logout',
      label: '退出登录',
      icon: <LogoutOutlined />,
      onClick: handleLogout
    }
  ];

  return (
    <>
      <Header
        style={{
          background: '#fff',
          boxShadow: '0 2px 8px rgba(0,0,0,0.05)',
          padding: '0 32px',
          height: 64,
          display: 'flex',
          alignItems: 'center',
          position: 'sticky',
          top: 0,
          zIndex: 99,
        }}
      >
        <Row style={{ width: '100%' }} align="middle" justify="space-between">
          {/* Logo & 菜单 */}
          <Col>
            <Space size="large">
              <Title
                level={4}
                style={{
                  margin: 0,
                  color: '#1677ff',
                  fontWeight: 'bold',
                  letterSpacing: 2,
                }}
              >
                接口管理系统
              </Title>
              <AppMenu />
            </Space>
          </Col>
          {/* 用户区 */}
          <Col>
            <Space>
              <Dropdown
                menu={{ items: userMenuItems }}
                open={userMenuVisible}
                onOpenChange={(visible) => setUserMenuVisible(visible)}
                trigger={['click']}
              >
                <div style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                  <Avatar
                    style={{
                      backgroundColor: token ? '#52c41a' : '#1677ff',
                      verticalAlign: 'middle',
                    }}
                    size={40}
                    icon={<UserOutlined />}
                  />
                  <span style={{ fontWeight: 500, fontSize: 16, marginLeft: 8 }}>
                    管理员 {token && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
                  </span>
                </div>
              </Dropdown>
            </Space>
          </Col>
        </Row>
      </Header>

      <TokenSettingModal
        visible={tokenModalVisible}
        onCancel={() => setTokenModalVisible(false)}
        onSave={handleSaveToken}
      />
    </>
  );
}

function App() {
  return (
    <HashRouter>
      <Layout
        style={{
          minHeight: '100vh',
          background: '#f5f7fa',
        }}
      >
        <AppHeader />
        <Content>
          <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<Db />} />
            <Route path="*" element={<Card style={{ marginTop: 32 }}><Title>页面未找到</Title></Card>} />
          </Routes>
        </Content>
      </Layout>
    </HashRouter>
  );
}

export default App;
